#include <iostream>
#include <fstream>
#include "Protocol.h"

using namespace SprotoType;

	int
	main(int argc, char *argv[])
{
	std::string pb;
	std::string filename = "sproto.spb";
	if (!LoadPbfile(filename, pb))
	{
		std::cout << "open addressbook.pb failed" << std::endl;
		return -1;
	}

	AddressBook abm;

	Person* jack = new Person;
	jack->SetId(100);
	jack->SetName("Jack");
	jack->SetEmail("jack@cartoon.com");
	PhoneNumber* phonenumber1 = new PhoneNumber;
	phonenumber1->SetNumber("001-123456");
	phonenumber1->SetType(1);	// telephone
	jack->AddPhoneNumber(phonenumber1);
	PhoneNumber* phonenumber2 = new PhoneNumber;
	phonenumber2->SetNumber("139xxxxxxxx");
	phonenumber2->SetType(2);	// mobile phone
	jack->AddPhoneNumber(phonenumber2);
	abm.AddPerson(jack);

	Person* tom = new Person;
	tom->SetId(101);
	tom->SetName("Tom");
	tom->SetEmail("tom@cartoon.com");
	abm.AddPerson(tom);
	std::cout << "abm1 dump:" << std::endl;
	// abm.Dump();

	static char buffer[1024];
	int size = sizeof(buffer);
	CppSproto sp;
	if (!sp.Init(pb.data(), pb.length()))
	{
		std::cout << "create CppSproto fail" << std::endl;
		return -1;
	}

	if (!sp.Encode(&abm, buffer, size))
	{
		std::cout << "Encode fail" << std::endl;
		if (size == -1)
		{
			std::cout << "buffer size is too small" << std::endl;
		}
		return -1;
	}

	// // SaveMsgfile("addressbook2.msg", sp.GetEncodedBuffer(), len);
	std::cout << "Encode ok.(" << size << " bytes)" << std::endl;

	AddressBook abm2;
	if (!sp.Decode(&abm2, buffer, size))
	{
		std::cout << "Decode fail" << std::endl;
		return -1;
	}

	std::cout << "Decode ok." << std::endl;

	// std::cout << "abm2 dump:" << std::endl;
	// abm2.Dump();
}

